<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item label="采购单编号" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入采购单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购计划ID" prop="planId">
        <el-input
          v-model="queryParams.planId"
          placeholder="请输入采购计划ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          clearable
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择创建时间"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['erp:purchase:edit']"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleCheck"
        >详情</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['erp:purchase:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['erp:purchase:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="purchaseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="采购单编号" align="center" prop="id" />
      <el-table-column label="采购计划ID" align="center" prop="planId" />
      <el-table-column label="总价" align="center" prop="sumCos" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['erp:purchase:edit']"
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAddHouse(scope.row)"
          >生成验货单</el-button>
          <el-button
            v-hasPermi="['erp:purchase:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCheck(scope.row)"
          >详情</el-button>
          <el-button
            v-hasPermi="['erp:purchase:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 采购单管理对话框详情 -->
    <el-dialog title="采购单详情" :visible.sync="openpurchase" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="总价" prop="finishTime">
          {{ form.sumCos }}
        </el-form-item>
        <el-divider content-position="center">采购计划物品信息</el-divider>
        <el-table ref="bPlanItem" :data="addPurchaseForm" :row-class-name="rowBPlanItemIndex" @selection-change="handleBPurchaseItemSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="150" />
          <el-table-column label="物品名称" align="center" prop="itemName" width="150" />
          <el-table-column label="计划数量" align="center" prop="purchaseNum" width="150" />
          <el-table-column label="供应商" align="center" prop="supName" width="150" />
          <el-table-column label="物品单价" align="center" prop="cost" width="150" />

        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 新增验货单 -->
    <el-dialog title="新增验货单" :visible.sync="openhouse" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-table ref="bPlanItem" :data="addHouseForm" :row-class-name="rowBPlanItemIndex" @selection-change="handleBPurchaseItemSelectionChange">
          <el-table-column label="物品ID" align="center" prop="id" width="150" />
          <el-table-column label="物品名称" align="center" prop="itemName" width="150" />
          <el-table-column label="实际进仓数量" prop="putNum" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.putNum" placeholder="实际进仓数量" />
            </template>
          </el-table-column>
          <el-table-column label="仓库名称" prop="houseId" width="200">
            <template slot-scope="scope">
              <el-select v-model="scope.row.houseId" placeholder="仓库名称">
                <el-option
                  v-for="item in houseoptions"
                  :key="item.houseId"
                  :label="item.houseName"
                  :value="item.houseId"
                />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { addPut_house } from '@/api/erp/puthouse/puthouse'
import { listWarehouse } from '@/api/erp/warehouse/warehouse'
import { listPurchase, getPurchase, delPurchase } from '@/api/erp/purchase/purchase'
import { getSupplier } from '@/api/erp/supplier/supplier'
export default {
  name: 'Purchase',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedBPurchaseItem: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购单管理表格数据
      purchaseList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      openpurchase: false,
      openhouse: false,
      purchaseoptions: [],
      addPurchaseForm: [],
      addHouseForm: [],
      houseoptions: [],
      purchaseId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        planId: null,
        createTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    }
  },
  created() {
    this.getList()
  },

  methods: {
    /** 查询采购单管理列表 */
    getList() {
      this.loading = true
      listPurchase(this.queryParams).then(response => {
        this.purchaseList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.openpurchase = false
      this.openhouse = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        planId: null,
        sumCos: null,
        createTime: null,
        isEnter: null,
        isDelete: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 生成验货单
    handleAddHouse(row) {
      this.reset()
      this.purchaseId = row.id
      getPurchase(row.id).then(res => {
        listWarehouse().then(res => {
          this.houseoptions = []
          res.rows.forEach(element => {
            this.houseoptions.push({
              houseId: element.id,
              houseName: element.houseName
            })
          })
        })
        this.addHouseForm = res.data.purchaseItemViewList
        this.openhouse = true
      })
    },
    /** 详情 */
    handleCheck(row) {
      this.reset()
      const id = row.id || this.ids
      getPurchase(id).then(response => {
        this.form = response.data
        this.addPurchaseForm = response.data.purchaseItemViewList
        for (let i = 0; i < this.addPurchaseForm.length; i++) {
          const element = this.addPurchaseForm[i]
          getSupplier(element.supplierId).then(res => {
            Object.assign(this.addPurchaseForm[i], { supName: res.data.supName })
            this.openpurchase = true
          })
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.openhouse = false
            this.openpurchase = false
          } else {
            var houseArr = []
            this.addHouseForm.forEach(element => {
              houseArr.push({
                itemId: element.id * 1,
                houseId: element.houseId * 1,
                putNum: element.putNum * 1
              })
            })
            console.log(houseArr)
            addPut_house({
              bPutItemList: houseArr,
              purchaseId: this.purchaseId * 1
            }).then(() => {
              this.cancel()
              this.$modal.msgSuccess('新增验货单成功')
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除采购单管理编号为"' + ids + '"的数据项？').then(function() {
        return delPurchase(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 采购单物品序号 */
    rowBPlanItemIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 复选框选中数据 */
    handleBPurchaseItemSelectionChange(selection) {
      this.checkedBPurchaseItem = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('erp/purchase/export', {
        ...this.queryParams
      }, `purchase_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
